package com.patentbackend.patentmanage.service.lmpl;

import com.patentbackend.patentmanage.dto.SliderDTO;
import com.patentbackend.patentmanage.entity.Slider;
import com.patentbackend.patentmanage.repository.SliderRepository;
import com.patentbackend.patentmanage.service.SliderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
public class SliderServiceImpl implements SliderService {

    @Autowired
    private SliderRepository sliderRepository;

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Override
    public Slider create(SliderDTO sliderDTO) {
        Slider slider = Slider.builder()
                .title(sliderDTO.getTitle())
                .description(sliderDTO.getDescription())
                .imageUrl(sliderDTO.getImageUrl())
                .linkUrl(sliderDTO.getLinkUrl())
                .sortOrder(sliderDTO.getSortOrder())
                .enabled(sliderDTO.getEnabled())
                .build();

        return sliderRepository.save(slider);
    }

    @Override
    public Slider update(Long id, SliderDTO sliderDTO) {
        Slider slider = sliderRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Slider not found with id: " + id));

        if (sliderDTO.getTitle() != null) slider.setTitle(sliderDTO.getTitle());
        if (sliderDTO.getDescription() != null) slider.setDescription(sliderDTO.getDescription());
        if (sliderDTO.getImageUrl() != null) slider.setImageUrl(sliderDTO.getImageUrl());
        if (sliderDTO.getLinkUrl() != null) slider.setLinkUrl(sliderDTO.getLinkUrl());
        if (sliderDTO.getSortOrder() != null) slider.setSortOrder(sliderDTO.getSortOrder());
        if (sliderDTO.getEnabled() != null) slider.setEnabled(sliderDTO.getEnabled());

        return sliderRepository.save(slider);
    }

    @Override
    public boolean existsById(Long id) {
        return sliderRepository.existsById(id);
    }

    @Override
    public List<Slider> findAll() {
        return sliderRepository.findAll();
    }

    @Override
    public List<Slider> findByEnabledOrderBySortOrderAsc(boolean enabled) {
        return sliderRepository.findByEnabledOrderBySortOrderAsc(enabled);
    }

    @Override
    public Optional<Slider> findById(Long id) {
        return sliderRepository.findById(id);
    }

    @Override
    public void delete(Long id) {
        sliderRepository.deleteById(id);
    }

    @Override
    public String uploadImage(Long sliderId, MultipartFile image) throws IOException {
        Slider slider = sliderRepository.findById(sliderId)
                .orElseThrow(() -> new RuntimeException("Slider not found with id: " + sliderId));

        // 创建轮播图目录
        Path uploadPath = Paths.get(uploadDir + "/sliders");
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 生成唯一文件名
        String fileName = UUID.randomUUID().toString() + "_" + image.getOriginalFilename();
        Path filePath = uploadPath.resolve(fileName);

        // 保存文件
        Files.copy(image.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

        // 更新图片URL
        slider.setImageUrl("/api/files/sliders/" + fileName);
        sliderRepository.save(slider);

        return slider.getImageUrl();
    }
}